package com.awccis.common.websocket;

import com.awccis.common.pool.DriverPool;
import com.awccis.common.session.DriverSession;
import com.awccis.common.utils.JsonUtil;
import com.google.gson.JsonObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.websocket.*;
import javax.websocket.server.ServerEndpoint;
import java.util.Date;

/**
 * @author: njpi
 * @description: 注解中的内容是用户客户端WebSocket的连接url, 例如ws://127.0.0.1:80/WebSocket/ws, 结构形式为“ws：//ip:端口/项目名/指定的url”
 */
@ServerEndpoint("/ws")
public class DriverWsServer {

    /**
     * 日志打印对象
     */
    private static Logger logger = LoggerFactory.getLogger(DriverWsServer.class);
    /**
     * key值
     */
    private static String key = "";

    private String compareStr = "0";
    private String driverSession = "driverSession";
    private String Geo = "Geo";

    /**
     * 连接打开时执行
     *
     * @param session session
     */
    @OnOpen
    public void onOpen(Session session) {
        //超时时间为20秒
        session.setMaxIdleTimeout(20000);
        System.out.println("一个司机客户端连接进来了 -----> 它的sessionId是：" + session.getId());
    }

    /**
     * 收到消息时执行
     *
     * @param message message
     * @param session session
     */
    @OnMessage
    public void onMessage(String message, Session session) {
        //如果消息头为0，立即发送消息
        if (compareStr.equals(message)) {
            session.getAsyncRemote().sendText(message);
        }else if (message.startsWith(driverSession)) {//如果消息头为driverSession
            String driver = message.split("&&")[1];
            DriverSession driverSession = JsonUtil.str2obj(driver,DriverSession.class);
            if(DriverPool.isContainById(driverSession.getDriverId())){
                driverSession.setOnLineTime(new Date());
                driverSession.setSession(session);
                DriverPool.deleteDriverById(driverSession.getDriverId());
                DriverPool.addDriverSession(session.getId(),driverSession);
            //    session.getAsyncRemote().sendText("ws:driverReOnlining");
                session.getAsyncRemote().sendText("0");
            }else{
                driverSession.setOnLineTime(new Date());
                driverSession.setSession(session);
                DriverPool.addDriverSession(session.getId(),driverSession);
                session.getAsyncRemote().sendText("ws:driverOnline");
            }

        } else if (message.contains(Geo)) {
            JsonObject obj = JsonUtil.str2obj(message, JsonObject.class);
            double lat = obj.getAsJsonObject(Geo).get("lat").getAsDouble();
            double lng = obj.getAsJsonObject(Geo).get("lng").getAsDouble();
            int driverId = obj.getAsJsonObject(Geo).get("driverId").getAsInt();
            DriverPool.updateLocation(driverId,lat,lng);
            session.getAsyncRemote().sendText("ws:refreshGeo");
            //System.out.println(obj.toString());
        }
    }

    /**
     * 连接关闭时执行
     *
     * @param session     session
     * @param closeReason closeReason
     */
    @OnClose
    public void onClose(Session session, CloseReason closeReason) {
        DriverSession driverSession = DriverPool.getDriverSession(session.getId());
        if(driverSession == null){
            logger.error("关闭错误!未获取连接对象!");
        }else{
            if(driverSession.isReady()){
                driverSession.setSession(null);
                logger.error("一个司机端关闭了，它的sessionId是：" + session.getId() + ";关闭原因是:" + closeReason.getReasonPhrase());
            }else{
                logger.error(driverSession.getDriverAliasName() + "司机下线啦");
                DriverPool.deleteDriverSession(session.getId());
            }
        }

    }
    
    /**
     * 连接错误时执行
     *
     * @param t 异常
     */
    @OnError
    public void onError(Throwable t) {
        t.printStackTrace();
    }

}
